<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="客户" prop="customerId">
            <el-select
              v-model="queryParams.customerId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入客户"
              :loading="loading"
              :remote-method="onSearching"
            >
              <el-option v-for="consumer in consumers" :key="consumer.id" :label="consumer.customerName" :value="consumer.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['sj:qrcode:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['sj:qrcode:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['sj:qrcode:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="qrcodeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="客户" align="center" prop="customerName" />
        <el-table-column label="二维码" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看二维码" placement="top">
              <el-button link type="primary" icon="PictureFilled" @click="handleCheckQrCode(scope.row.imageId)"></el-button>
            </el-tooltip>
            <el-tooltip content="下载二维码" placement="top">
              <el-button link type="primary" icon="Download" @click="downLoadQrCode(scope.row.imageId)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="关联资源" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-link @click="handleCheckVideo(scope.row.fileId)" type="primary">{{scope.row.filesVo[0].originalName}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="点击次数" align="center" prop="count" />
        <el-table-column label="操作人" align="center" prop="updateByName" />
        <el-table-column label="操作时间" align="center" prop="updateTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sj:qrcode:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sj:qrcode:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改二维码管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="qrcodeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户" prop="customerId">
          <!--          <el-input v-model="form.customerId" placeholder="请选择客户" />-->
          <el-select
            v-model="form.customerId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入客户"
            :loading="loading"
            :remote-method="onSearching"
          >
            <el-option v-for="consumer in consumers" :key="consumer.id" :label="consumer.customerName" :value="consumer.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联资源" prop="fileId">
          <file-upload v-model="form.fileId" />
        </el-form-item>
        <el-form-item label="生成二维码" label-width="100px" prop="imageId">
          <el-button type="primary" :loading="generateLoading" :disabled="!form.imageId?false:true" @click="generateCode">点击生成二维码</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-image-viewer
      infinite
      :hide-on-click-modal="true"
      @close="closeImageViewer"
      :url-list="(qrcodeSrcList as string[])"
      :initial-index="0"
      v-if="showImageViewer"
    ></el-image-viewer>
  </div>
</template>

<script setup name="Qrcode" lang="ts">
import { listQrcode, getQrcode, delQrcode, addQrcode, updateQrcode,generateQrcode,downloadQrcode, checkQrCode } from '@/api/sj/qrcode';
import { getConsumer } from '@/api/sj/customer/index';
import { QrcodeVO, QrcodeQuery, QrcodeForm } from '@/api/sj/qrcode/types';
import { CustomerVO, getConsumerData} from '@/api/sj/customer/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const qrcodeList = ref<QrcodeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const imgSrc = ref();
const isGeneratedCode = ref(false);
const consumers = ref<CustomerVO[]>();
const queryFormRef = ref<ElFormInstance>();
const qrcodeFormRef = ref<ElFormInstance>();
const qrcodeSrcList = ref<string[]>([]);
const showImageViewer = ref(false);
const generateLoading = ref(false);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const getCustomerData = reactive<getConsumerData>({
  customerName:''
})

const initFormData: QrcodeForm = {
  id: undefined,
  customerId: undefined,
  imageId: undefined,
  fileId: undefined,
  url: undefined,
}
const data = reactive<PageData<QrcodeForm, QrcodeQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerId: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    customerId: [
      { required: true, message: "客户不能为空", trigger: "blur" }
    ],
    imageId: [
      { required: true, message: "二维码不能为空", trigger: "blur" }
    ],
    fileId: [
      { required: true, message: "关联资源不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询二维码管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listQrcode(queryParams.value);
  qrcodeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/*查询客户信息*/
const getCustomerByName = async (data:getConsumerData)=>{
  const res = await getConsumer(data);
  consumers.value = res.data;
}

/*预览二维码*/
const handleCheckQrCode = async (id: string)=>{
  const res = await checkQrCode(id);
  const qrCodeList = new Array(res.data);
  if(qrCodeList?.length){
    showImageViewer.value = true;
    qrcodeSrcList.value = qrCodeList;
  }else{
    showImageViewer.value = false;
    ElMessage.error('未生成二维码');
  }
};

const closeImageViewer = ()=>{
  showImageViewer.value = false;
  qrcodeSrcList.value = [];
}

/* 下载二维码 */
const downLoadQrCode = async(id:number | string)=>{
  await downloadQrcode(id).then((res)=>{
    const blob = new Blob([res as any]);
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = (e)=>{
      const aElement = document.createElement('a');
      aElement.download = 'qrCode.png';
      aElement.href = (e?.target?.result) as string;
      document.body.appendChild(aElement);
      aElement.click();
      document.body.removeChild(aElement);
    };
  });
}

/*预览视频*/
const handleCheckVideo = async (id:string)=>{
  const res = await checkQrCode(id);
  window.open(res.data);
}


const onSearching = (query:string)=>{
  getCustomerData.customerName = query;
  // consumerQuery.customerName = query;
  // getConsumers(consumerQuery);
  getCustomerByName(getCustomerData);
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  qrcodeFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: QrcodeVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加二维码管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: QrcodeVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getQrcode(_id);
  // console.log(res.data);
  Object.assign(form.value, res.data);
  // console.log(form.value);
  dialog.visible = true;
  dialog.title = "修改二维码管理";
}

/*点击生成二维码*/
const generateCode = async ()=>{
  if(form.value.fileId){
    generateLoading.value = true;
    await generateQrcode(form.value.fileId).then((res)=>{
      imgSrc.value = res.data.url;
      form.value.imageId = res.data.ossId;
      generateLoading.value = false;
      ElMessage({
        message: '生成二维码成功，请在列表中预览',
        type: 'success',
      });
    });
  }else{
    ElMessage({
      message: '未上传文件，上传文件后可生成二维码',
      type: 'warning',
    });
  }
};

const handleDownload = (id:string)=>{
  proxy?.download(`/resource/oss/download`, {
    id:id
  }, `qrCode`)
}

/** 提交按钮 */
const submitForm = () => {
  qrcodeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateQrcode(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addQrcode(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
      isGeneratedCode.value = false;
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: QrcodeVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除二维码管理编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delQrcode(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}



onMounted(() => {
  getList();
});
</script>
